package indi.lqzhi.basic.ui.basic.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;


public abstract class AbstarctRecycleViewAdapter<Bind extends ViewDataBinding,Data> extends RecyclerView.Adapter<AbstarctRecycleViewAdapter.ViewHolder<Bind>> {

    protected Context context;

    protected List<Data> dataList;

    public AbstarctRecycleViewAdapter(Context context){
        this.context = context;
        dataList = Collections.emptyList();
    }


    public AbstarctRecycleViewAdapter(Context context, List<Data> dataList){
        this.context = context;
        this.dataList = CollectionUtils.isEmpty(dataList) ? Collections.emptyList() : dataList;
    }


    public AbstarctRecycleViewAdapter(Context context, Data []datas){
        this.context = context;
        this.dataList = (datas == null || datas.length <= 0) ? Collections.emptyList() : Arrays.asList(datas);
    }

    @NonNull
    @Override
    public ViewHolder<Bind> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder<>(DataBindingUtil.inflate(LayoutInflater.from(context),getLayoutId(),parent,false));
    }

    public abstract void onBind(Bind bindView,Data datas,@NonNull ViewHolder<Bind> holder, int position);

    @Override
    public void onBindViewHolder(@NonNull ViewHolder<Bind> holder, int position){
        onBind(holder.bindView, dataList.get(position),holder,position);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public abstract int getLayoutId();

    protected static class ViewHolder<Bind extends ViewDataBinding> extends RecyclerView.ViewHolder{

        Bind bindView;

        private ViewHolder(Bind bindView){
            super(bindView.getRoot());
            this.bindView = bindView;
        }

        public Bind getBindView() {
            return bindView;
        }
    }

    public void setDataList(List<Data> dataList) {
        this.dataList = dataList;
    }
}
